using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace DBLGen
{
	public class TableCollection : ICollection<Table>
	{
		private Project _project;
		private List<Table> _items = new List<Table>();

		public List<Table> Items
		{
			get
			{
				return _items;
			}
			internal set
			{
				_items = value;
			}
		}

		internal TableCollection()
		{
		}

		public TableCollection(Project project)
		{
			if (project == null)
				throw new ArgumentNullException("project");

			_project = project;
		}

		public Table[] SelectBySourceType(TableSourceType type)
		{
			List<Table> tables = new List<Table>();

			foreach (Table t in Items)
				if (t.SourceType == type)
					tables.Add(t);

			return tables.ToArray();
		}

		public Table Find(string schema, string tableName)
		{
			if (schema == null)
				schema = String.Empty;

			foreach (Table t in Items)
				if (String.Compare(t.Schema, schema, true) == 0 && String.Compare(t.Name, tableName, true) == 0)
					return t;

			return null;
		}

		public Table[] ToArray()
		{
			return Items.ToArray();
		}

		#region ICollection<Table> Members

		public void Add(Table item)
		{
			if (String.IsNullOrEmpty(item.Name))
				throw new ArgumentNullException("A table must have a name to be added to the TableCollection.");

			Items.Add(item);
			item.Project = _project;
		}

		public void AddRange(IEnumerable<Table> items)
		{
			foreach (Table item in items)
				Add(item);
		}

		public void Clear()
		{
			Items.Clear();
		}

		public bool Contains(Table item)
		{
			return Items.Contains(item);
		}

		public void CopyTo(Table[] array, int arrayIndex)
		{
			Items.CopyTo(array, arrayIndex);
		}

		public int Count
		{
			get
			{
				return Items.Count;
			}
		}

		public bool IsReadOnly
		{
			get
			{
				return false;
			}
		}

		public bool Remove(Table item)
		{
			return Items.Remove(item);
		}

		#endregion

		#region IEnumerable<Table> Members

		public IEnumerator<Table> GetEnumerator()
		{
			return (IEnumerator<Table>)Items.GetEnumerator();
		}

		#endregion

		#region IEnumerable Members

		IEnumerator IEnumerable.GetEnumerator()
		{
			return this.GetEnumerator();
		}

		#endregion

	}
}
